<template>
    <basic-container>
        <avue-crud
            :option='option'
            :table-loading='loading'
            v-model='form'
            :data='data'
            :page.sync='page'
            :permission='permissionList'
            :before-open='beforeOpen'
            :search.sync='query'
            ref='crud'
            @row-update='rowUpdate'
            @row-save='rowSave'
            @row-del='rowDel'
            @search-change='searchChange'
            @search-reset='searchReset'
            @selection-change='selectionChange'
            @current-change='currentChange'
            @size-change='sizeChange'
            @refresh-change='refreshChange'
            @on-load='onLoad'
        >
            <template slot='menuLeft' slot-scope='{ row }'>
                <el-button type='primary' icon='el-icon-printer' size='small' @click='handlePrint()'
                           :disabled='selectionList.length === 0'>打印
                </el-button>
            </template>
            <template slot='menuRight'>
                <user-table-config :option='option'
                                   @confirm='(val) => handleSetUserConfig(val, pageCode)'></user-table-config>
            </template>
            <template slot='menu' slot-scope='{ row }'>
                <el-button icon='el-icon-view' size='small' type='text' @click='rowView(row)'>详情</el-button>
            </template>
        </avue-crud>
        <el-dialog append-to-body title='打印条码' v-if='printInfoModel' :visible.sync='printInfoModel' width='35%'>
            <avue-form ref='printForm' v-model='printInfo' :option='printInfoOption'></avue-form>
            <span slot='footer' class='dialog-footer'>
        <el-button size='small' type='primary' @click='printSubmit'><i
            class='el-icon-printer'></i><span>打 印</span></el-button>
        <el-button size='small' @click='printInfoModel = false'><i
            class='el-icon-circle-close'></i><span>关 闭</span></el-button>
      </span>
        </el-dialog>
        <el-dialog append-to-body title='详情' v-if='detailVisible' :visible.sync='detailVisible' width='60%' top='3vh'>
            <div class='sail-header-dialog-content'>
                <avue-form ref='printForm' v-model='detailForm' :option='detailOption'>
                    <template slot='send'>
                        <div class='send-detail'>
                            <div class='title'>
                                <div class='text'>客户名称:{{ detailForm.vendorName }}</div>
                                <div class='text'>送货单:{{ detailForm.scmDeliverySheetNo }}</div>
                            </div>
                            <avue-crud ref='reloadCrud' :option='sendTableOption'
                                       :data='detailForm.scmDeliverySheetDetail || []'></avue-crud>
                        </div>
                    </template>
                    <template slot='pack'>
                        <el-row>
                            <el-col :span='24'>
                                <span class='color-text'> *</span>包装层级：
                                <el-input style='width: 150px; margin-right: 40px' disabled
                                          v-model='detailForm.packLevel'></el-input>
                                <span class='color-text'> *</span>序列号规则:
                                <el-input disabled style='width: 250px'
                                          v-model='detailForm.scmPackConfig.sequenceRule'></el-input>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span='24'>
                                <p class='p-title'>包装层级1(小包):</p>
                                1个小包，装<span class='color-text'> *</span>
                                <el-input style='width: 150px' disabled
                                          v-model='detailForm.scmPackConfig.packLevel1ProductCount' />
                                个产品
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span='24'>
                                <p class='p-title'>包装层级2(大包):</p>
                                1个大包，装 <span class='color-text'> *</span>
                                <el-input style='width: 150px' disabled
                                          v-model='detailForm.scmPackConfig.packLevel2ProductCount' />
                                个小包
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span='24'>
                                <p class='p-title'>包装层级3(外箱):</p>
                                1个外箱，装<span class='color-text'> *</span>
                                <el-input style='width: 150px' disabled
                                          v-model='detailForm.scmPackConfig.packLevel3ProductCount' />
                                个大包
                            </el-col>
                        </el-row>
                    </template>
                    <template slot='detail'>
                        <avue-crud ref='reloadCrud' :table-loading='detailLoading' :option='barcodeDetailOption'
                                   :data='detailData' :page.sync='detailPage' @current-change='detailCurrentChange'
                                   @size-change='detailSizeChange'>
                            <template slot='smallPackNoHeader' slot-scope='{ column }'>
                                <div class='pack-number'>小包条码</br>({{ detailForm.smallPackNo || 0 }})</div>
                            </template>

                            <template slot='smallPackQuantityHeader' slot-scope='{ column }'>
                                <div class='pack-number'>小包包装数量</br>
                                    包规数量:{{ detailForm.smallPackSpec || 0 }}
                                </div>
                            </template>

                            <template slot='bigPackNoHeader' slot-scope='{ column }'>
                                <div class='pack-number'>大包条码</br>
                                    ({{ detailForm.bigPackNo || 0 }})
                                </div>
                            </template>

                            <template slot='bigPackQuantityHeader' slot-scope='{ column }'>
                                <div class='pack-number'>大包包装数量</br>
                                    包规数量：{{ detailForm.bigPackSpec || 0 }}
                                </div>
                            </template>

                            <template slot='outerBoxPackNoHeader' slot-scope='{ column }'>
                                <div class='pack-number'>外箱条码</br>
                                    ( {{ detailForm.outerBoxPackNo || 0 }})
                                </div>
                            </template>

                            <template slot='outerBoxPackQuantityHeader' slot-scope='{ column }'>
                                <div class='pack-number'>外箱包装数量</br>
                                    包规数量：{{ detailForm.outBoxPackSpec || 0 }}
                                </div>
                            </template>
                        </avue-crud>
                    </template>
                </avue-form>
            </div>
            <span slot='footer' class='dialog-footer'>
        <el-button size='small' @click='detailVisible = false'><i
            class='el-icon-circle-close'></i><span>关 闭</span> </el-button>
      </span>
        </el-dialog>
        <common-modal-template ref='commonModalTemplate' :option='tableOption' @getSelectedRows='getSelectedRows'
                               :key='timer' @newKey='newKey'></common-modal-template>
    </basic-container>
</template>
<script>
import { mapGetters } from 'vuex';
import userTableConfig from '@/components/user-table-config/index.vue';
import userConfig from '@/mixins/userConfig';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';

import { getList, getDetail, getLabelInfo, printSn, getDetailList } from '@/api/scm/barcodeManage';
import { detailOption, option, sendTableOption, barcodeDetailOption } from '@/views/scm/barcodeMangeOption';

export default {
    name: 'barCodeManage', // 会渲染成传入的componentName
    components: {
        userTableConfig,
        CommonModalTemplate
    },
    mixins: [userConfig()],
    data() {
        return {
            scmDeliverySheetItemId:'',
            printInfoModel: false,
            timer: new Date().getTime(),
            tableOption: {},
            printInfo: '',
            printInfoOption: {
                labelWidth: 150,
                submitBtn: false,
                emptyBtn: false,
                column: [
                    {
                        label: '打印机',
                        prop: 'equipmentName',
                        span: 20,
                        type: 'search',
                        placeholder: '请选择 打印机',
                        disabled: true,
                        rules: [
                            {
                                required: true,
                                message: '请选择打印机',
                                trigger: 'blur'
                            }
                        ],
                        appendClick: () => {
                            this.openPrintersModal();
                        }
                    },
                    {
                        label: '标签模版',
                        prop: 'labelTemplateName',
                        span: 20,
                        type: 'search',
                        placeholder: '请选择 标签模板',
                        disabled: true,
                        rules: [
                            {
                                required: true,
                                message: '请选择标签模板',
                                trigger: 'blur'
                            }
                        ],
                        appendClick: () => {
                            this.openLabelTemplateModal();
                        }
                    }
                ]
            },
            selectionList: [],
            detailForm: {
                scmPackingDetailList: []
            },
            detailVisible: false,
            form: {},
            query: {},
            loading: true,
            page: {
                pageSize: 20,
                currentPage: 1,
                total: 0
            },
            detailPage: {
                pageSize: 20,
                currentPage: 1,
                total: 0
            },
            detailLoading: true,
            data: [],
            detailData: [],
            detailOption,
            option,
            sendTableOption,
            barcodeDetailOption
        };
    },
    mounted() {
        this.$nextTick(() => {
            this.$structuralSplit();
        });
    },
    computed: {
        ...mapGetters(['permission']),
        permissionList() {
            return {
                addBtn: this.vaildData(this.permission, false),
                viewBtn: this.vaildData(this.permission, false),
                delBtn: this.vaildData(this.permission, false),
                editBtn: this.vaildData(this.permission, false)
            };
        }
    },
    methods: {
        rowSave(row, done, loading) {
        },
        rowUpdate(row, index, done, loading) {
        },
        rowDel(row) {
        },
        beforeOpen(done, type) {
        },
        searchReset() {
            this.query = {};
            this.onLoad(this.page);
        },
        searchChange(params, done) {
            this.query = params;
            this.page.currentPage = 1;
            this.onLoad(this.page, params);
            done();
        },
        /**
         * 获取打印机
         */
        openPrintersModal() {
            this.modalName = 'printersModal';
            this.$refs.commonModalTemplate.showModal();
            this.tableOption = {
                modalTitle: '选择打印机（双击进行选择）',
                url: '/api/mes-product/scm-printer/page-query',
                isPage: true,
                rowSelectionType: 'single',
                columnDefs: [
                    {
                        label: '打印机编码',
                        prop: 'code',
                        search: true,
                        searchLabelWidth: 110
                    },
                    {
                        label: '打印机名称',
                        prop: 'name',
                        search: true,
                        searchLabelWidth: 110
                    }
                ]
            };
        },
        /**
         * 打开标签模板模态框
         */
        openLabelTemplateModal() {
            this.modalName = 'labelTemplateModal';
            this.$refs.commonModalTemplate.showModal();
            this.tableOption = {
                modalTitle: '选择标签模版（双击进行选择）',
                url: '/api/mes-admin/labeltemplate/list-by-partnerid',
                isPage: true,
                query:{partnerId:this.selectionList[0].partnerId},
                rowSelectionType: 'single',
                columnDefs: [
                    {
                        label: '标签名称',
                        prop: 'fileName',
                        search: true
                    },
                    {
                        label: '标签代码',
                        prop: 'code',
                        search: true
                    },
                    {
                        label: '版本名称',
                        prop: 'revision'
                    },
                    {
                        label: '缩略图',
                        prop: 'thumbnailUrl'
                    },
                    {
                        label: '打印标签',
                        prop: 'fileUrl'
                    }
                ]
            };
        },
        newKey() {
            this.timer = new Date().getTime();
        },
        getSelectedRows(rowData, title) {
            switch (this.modalName) {
                case 'labelTemplateModal':
                    this.$set(this.printInfo, 'labelTemplateId', rowData.id);
                    this.$set(this.printInfo, 'labelTemplateName', rowData.fileName);
                    break;
                case 'printersModal':
                    this.$set(this.printInfo, 'equipmentId', rowData.id);
                    this.$set(this.printInfo, 'equipmentName', rowData.name);
                    break;
                default:
                    break;
            }
        },
        async rowView(row) {
            try {
                const res = await getDetail({
                    scmDeliverOrderId: row.scmDeliverySheetId,
                    scmDeliverSheetItemId:row.scmDeliverySheetItemId
                });
                this.detailForm = {
                    ...res.data.data,
                    scmDeliverySheetNo: row.scmDeliverySheetNo,
                    vendorName: row.vendorName
                };
                this.scmDeliverySheetItemId = row.scmDeliverySheetItemId
                await this.getListInfo();
                this.detailVisible = true;
            } catch (e) {
                console.log(e);
            }
        },
        async getListInfo() {
            try {
               // const scmDeliveryItemIds = this.detailForm.scmDeliverySheetDetail.map(i => i.sheetItemId).join(',');
                const params = {
                    scmDeliveryItemId:this.scmDeliverySheetItemId,
                    current: this.detailPage.currentPage,
                    size: this.detailPage.pageSize
                };
                this.detailLoading = true;
                const res = await getDetailList(params);
                const data = res.data.data;
                this.detailPage.total = data.total;
                this.detailData = data.records;
            } catch (e) {
                console.log(e);
            } finally {
                this.detailLoading = false;

            }
        },
        async handlePrint() {
            if (this.selectionList.length > 1) {
                const isCanPrint = this.checkEquality(this.selectionList);
                if (!isCanPrint) {
                    this.$message.warning('批量打印的条码需为同个送货单、同个送货明细、同个层级，请重新选择！');
                    return;
                } else {

                        const isSameLabel = this.checkLabelModel(this.selectionList);
                        const isSameEquipment = this.checkPrint(this.selectionList);
                        if (isSameLabel&&this.selectionList[0].lastPrintLabelTemplateId) {
                            this.printInfo={
                                labelTemplateId:this.selectionList[0].lastPrintLabelTemplateId,
                                labelTemplateName:this.selectionList[0].lastPrintLabelTemplateName
                            }
                        } else {
                            //客户给本供应商配置的模板有多个，默认显示列表第一个（最上方的那个） 查接口
                            const labelInfo = await this.getLabelTemplate( this.selectionList[0].partnerId);
                            if (labelInfo.length > 0) {
                                this.printInfo={
                                    labelTemplateId: labelInfo[0].id,
                                    labelTemplateName:labelInfo[0].fileName
                                }
                                // this.printInfo.labelTemplateId = labelInfo[0].id;
                                // this.printInfo.labelTemplateName = labelInfo[0].fileName;
                            }
                        }
                        if (isSameEquipment) {
                            Object.assign(this.printInfo,{equipmentId:this.selectionList[0].lastPrintPrinterId})
                            // this.printInfo.equipmentId = this.selectionList[0].lastPrintPrinterId;
                        }
                }
            } else {
                const row = this.selectionList[0];
                let labelTemplateId, labelTemplateName;
                if (!row.labelTemplateId) {
                    const defaultInfoArr = await this.getLabelTemplate(row.partnerId);
                    if (defaultInfoArr.length) {
                        const defaultInfo = defaultInfoArr[0];
                        labelTemplateId = defaultInfo.id;
                        labelTemplateName = defaultInfo.fileName;
                    }
                } else {
                    labelTemplateId = row.lastPrintLabelTemplateId || '';
                    labelTemplateName = row.lastPrintLabelTemplateName || '';
                }
                this.printInfo = {
                    labelTemplateId: labelTemplateId,
                    labelTemplateName: labelTemplateName,
                    equipmentId: row.lastPrintPrinterId || '',
                    equipmentName: row.lastPrintPrinterName || ''
                };
            }
            console.log('this.printInfoModel');
            this.printInfoModel = true;
        },
        async getLabelTemplate(partnerId) {
            try {
                const res = await getLabelInfo({ partnerId });
                return res.data.data;
            } catch (e) {
                return [];
            }
        },
        checkEquality(arr) {
            for (let i = 0; i < arr.length - 1; i++) {
                if (
                    arr[i].scmDeliverySheetNo !== arr[i + 1].scmDeliverySheetNo ||
                    arr[i].packLevel !== arr[i + 1].packLevel ||
                    arr[i].scmDeliverySheetItemId !== arr[i + 1].scmDeliverySheetItemId
                ) {
                    return false;
                }
            }
            return true;
        },
        checkLabelModel(arr) {
            for (let i = 0; i < arr.length - 1; i++) {
                if (arr[i].lastPrintLabelTemplateId !== arr[i + 1].lastPrintLabelTemplateId) {
                    return false;
                }
            }
            return true;
        },
        checkPrint(arr) {
            for (let i = 0; i < arr.length - 1; i++) {
                if (arr[i].lastPrintPrinterId !== arr[i + 1].lastPrintPrinterId) {
                    return false;
                }
            }
            return true;
        },
        selectionChange(list) {
            this.selectionList = list;
        },
        selectionClear() {
            this.selectionList = [];
            this.$refs.crud.toggleSelection();
        },
        printSubmit() {
            this.$refs.printForm.validate((valid, done) => {
                if (valid) {
                    let data = {
                        sequenceDetailList: this.selectionList.map((item) => {
                            return {
                                sequenceGenerationId: item.sequenceGenerationId,
                                sequenceNumber: item.packNo
                            };
                        }),
                        equipmentId: this.printInfo.equipmentId,
                        labelTemplateId: this.printInfo.labelTemplateId
                    };
                    printSn(data).then(
                        (res) => {
                            this.$refs.printForm.resetForm();
                            this.printInfoModel = false;
                            this.$message({
                                type: 'success',
                                message: res.data.msg
                            });
                            this.onLoad(this.page);
                            done();
                        },
                        (error) => {
                            done();
                        }
                    );
                }
            });
        },
        currentChange(currentPage) {
            this.page.currentPage = currentPage;
        },
        sizeChange(pageSize) {
            this.page.pageSize = pageSize;
        },
        detailSizeChange() {
            this.detailPage.pageSize = pageSize;
            this.getListInfo();
        },
        detailCurrentChange(currentPage) {
            this.detailPage.currentPage = currentPage;
            this.getListInfo();
        },
        refreshChange() {
            this.onLoad(this.page, this.query);
        },
        async onLoad(page, params = {}) {
            if (this.query.packNoGenerationTime && this.query.packNoGenerationTime.length) {
                this.query.packGenerationStartTime = this.$moment(this.query.packNoGenerationTime[0]).format('YYYY-MM-DD HH:mm:ss');
                this.query.packGenerationEndTime = this.$moment(this.query.packNoGenerationTime[1]).format('YYYY-MM-DD HH:mm:ss');
                delete this.query.packNoGenerationTime;
            }
            this.loading = true;
            try {
                const res = await getList(page.currentPage, page.pageSize, Object.assign(params, this.query));
                const data = res.data.data;
                this.page.total = data.total;
                this.data = data.records;
                this._forEach(this.data, (item) => {
                    item.packStatus = String(item.packStatus);
                    item.packLevel = String(item.packLevel);
                    item.printStatus = String(item.printStatus);
                });
            } catch (e) {
                console.warn(e);
            } finally {
                this.loading = false;
            }
        }
    }
};
</script>
<style lang='scss' scoped>
.send-detail {
    .title {
        display: flex;
        font-size: 16px;
        font-weight: bold;
        color: red;

        .text {
            width: 50%;
        }
    }
}

.sail-header-dialog-content {
    ::v-deep .avue-crud__menu {
        display: none;
    }
}

.p-title {
    font-weight: bold;
    display: inline-block;
}

.color-text {
    color: red;
}

.pack-number {
    text-align: center;
}
</style>
